const router = require('koa-router')()
const db = require('./lib/mysql')
const { checkParms } = require('./lib/parmsCheck')
const makeResult = require('./lib/makeResult')
const helper = require('./lib/helper')
const bt = require('./lib/bt')
router.prefix('/admin')

async function cookieToUser(ctx, power) {
  let token = ctx.cookies.get('token')
  if (!token) return makeResult.fail(ctx, 'token不存在', 303)
  let userInfo = (await db.query(`select * from admin where token=?`, [token]))[0]
  if (userInfo.length == 0) return makeResult.fail(ctx, 'token失效', 303)
  userInfo = userInfo[0]
  if (power && power.indexOf(userInfo.power) == -1) return makeResult.fail(ctx, '权限不足', 304)
  return userInfo
}

router.post('/login', async function (ctx, next) {
  const parms = ctx.query
  const body = ctx.request.body

  const { user, password } = body
  let checkParmsResulu = checkParms({ user, password }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = (await db.query(`select _id from admin where userid=? and password=?`, [user, password]))[0]
  if (userInfo.length == 0) return makeResult.fail(ctx, '账户或密码错误')

  const newToken = helper.makeRandomString(32)
  await db.query(`update admin set token=?,tokentime=? where _id=?`, [newToken, new Date().getTime(), userInfo[0]._id])
  ctx.cookies.set('token', newToken)

  ctx.body = makeResult.sucess(ctx)
})

router.post('/loginOut', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  await db.query(`update admin set token=? where _id=?`, ['', userInfo._id])
  ctx.cookies.set('token', '')

  ctx.body = makeResult.sucess(ctx)
})

router.get('/cookieLogin', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return
  let { userid, token, power } = userInfo
  ctx.body = makeResult.sucess(ctx, { userid, token, power })
})

router.get('/getUsers', async (ctx, next) => {
  const { page, count, user } = ctx.query
  let checkParmsResulu = checkParms({ page, count }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx, [1])
  if (userInfo?.code) return

  let where = ''
  if (user) where = helper.makeDBWhere({ user: `'${user}'` })
  let list = (await db.query(`select * from users ${where} limit ?,?`, [parseInt(page) * parseInt(count), parseInt(count)]))[0]

  ctx.body = makeResult.sucess(ctx, list)
})

router.post('/editClass', async (ctx, next) => {
  const { classList } = ctx.request.body
  let checkParmsResulu = checkParms({ classList }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx, [1])
  if (userInfo?.code) return

  await db.query(`update configs set value=? where name='class'`, [JSON.stringify(classList)])

  ctx.body = makeResult.sucess(ctx)
})

router.post('/editSwiper', async (ctx, next) => {
  const { typeid, list } = ctx.request.body
  let checkParmsResulu = checkParms({ typeid }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx, [1])
  if (userInfo?.code) return

  if (typeof list != 'object') return makeResult.fail(ctx, '类型出现问题')
  if (list.length != 0) {
    for (let v of list) {
      let { _id, vod_name, vod_info, vod_index, vod_img_small, vod_img, type_id } = v
      if (typeid != type_id) return makeResult.fail(ctx, '类型出现问题')
      let checkParmsResulu = checkParms({ _id, vod_name, vod_info, vod_index, vod_img_small, vod_img, type_id }, ctx)
      if (checkParmsResulu != true) return makeResult.fail(ctx, '不可上传空参数的轮播，请重新检查')
    }
  }
  await db.query(`delete from configs where name=?`, [`swiper_${typeid}`])
  await db.query(`insert into configs (name,value) values (?,?)`, [`swiper_${typeid}`, JSON.stringify(list)])

  ctx.body = makeResult.sucess(ctx)
})

router.post('/configSet', async (ctx, next) => {
  const { key, value } = ctx.request.body
  let checkParmsResulu = checkParms({ key, value }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx, [1])
  if (userInfo?.code) return

  await db.query(`update configs set value=? where name=?`, [typeof value == Object ? JSON.stringify(value) : value, key])

  ctx.body = makeResult.sucess(ctx)
})

router.get('/siteReport', async (ctx, next) => {
  const { date } = ctx.query
  let checkParmsResulu = checkParms({ date }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  let res_ = await bt.btFuc('/plugin?action=a&s=get_all_site&name=total', `query_date=${date}`)
  try {
    return makeResult.sucess(ctx, res_.data)
  } catch (error) {}
  return makeResult.fail(ctx, '获取失败')
})

router.get('/apiReport', async (ctx, next) => {
  const { date } = ctx.query
  let checkParmsResulu = checkParms({ date }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  let res_ = await bt.btFuc('/plugin?action=a&name=total&s=get_client_stat', `site=nodejsReptile&query_date=${date}&target=top&time_scale=day&request_in_panel=True`)
  try {
    return makeResult.sucess(ctx, res_.data)
  } catch (error) {}
  return makeResult.fail(ctx, '获取失败')
})

module.exports = router
